﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using Wicture.DbRESTFul.SQL;
using Wicture.EPC.Common;
using Wicture.EPC.Service.V1.Models;
using Wicture.EPC.Service.V1.Repository;

namespace Wicture.EPC.Service.V1.QueryInterceptors.Interceptors
{
    public class SgmwQueryInterceptor : BaseQueryInterceptor
    {
        public override string[] BrandCodes { get; } = new string[] { "sgmw", "baojun" };

        protected override IEnumerable<dynamic> GetHotPoints(DbRESTFulRepository repository, JObject param)
        {
            return repository.Invoke(CSIs.Query_HotPoints_Standard, param);
        }

        protected override List<Query_MainGroupResult> GetMainGroup(DbRESTFulRepository repository, JObject param)
        {
            return repository.Invoke<Query_MainGroupResult>(CSIs.Query_Main_Group_For_Sgmw, param);
        }

        protected override IEnumerable<Query_SubGroupResult> GetSubGroup(DbRESTFulRepository repository, JObject param)
        {
            return repository.Invoke<Query_SubGroupResult>(CSIs.Query_SubGroup_For_Sgmw, param);
        }

        protected override List<Query_PartsResult> GetParts(DbRESTFulRepository repository, JObject param)
        {
            return repository.Invoke<Query_PartsResult>(CSIs.Query_Parts_For_Sgmw, param);
        }

        protected override void FilterPartsByVin(DbRESTFulRepository repository, ref List<Query_PartsResult> result, string vin, string selectorId)
        {
            
        }

        protected override List<Query_PartsResult> BuildPartResults(List<Query_PartsResult> result)
        {
            foreach (var info in result)
            {
                info.notes += $"$${info.firstYear} - {info.lastYear}";
                if (!string.IsNullOrEmpty(info.hand))
                {
                    info.notes += $"$${info.hand}";
                }
                if (info.notes != null && info.notes.StartsWith("$$"))
                {
                    info.notes = info.notes.Substring(2);
                }
            }
            return result.Select(q => new Query_PartsResult { id = q.id, brandCode = q.brandCode, brandName = q.brandName, belongToVin = true, imageSN = q.imageSN, partCode = q.partCode, partName = q.partName, quantity = q.quantity, notes = q.notes, modelNotes = q.modelNotes, price = q.price, cost = q.cost, priceUpdatedAt = q.priceUpdatedAt, replacedPartCodes = q.replacedPartCodes }).ToList();
        }

        protected override SubGroupInfo GetSubGroupForCrumb(DbRESTFulRepository repository, JObject param)
        {
            return repository.Invoke<SubGroupInfo>(CSIs.Get_SubGroup_By_Id_Standard, param);
        }

        /// <summary>
        /// 5、获取配件详情
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public override object QueryPartDetail(DbRESTFulRepository repository, JObject param)
        {
            param.RemoveEmptyValues();
            var brandCode = param.Value<string>(ParamFields._brandCode);
            var partId = param.Value<string>(ParamFields._partId);
            dynamic data = null;
            if (string.IsNullOrEmpty(partId))
            {
                data = repository.Invoke(CSIs.Get_Part_Detail_Standard, param);
            }
            else
            {
                data = repository.Invoke(CSIs.Get_Usage_Detail_Standard, param);
            }
            if (data == null) return null;
            // 1、基本信息赋值
            Query_Part_DetailResult result = JObject.FromObject(data).ToObject<Query_Part_DetailResult>();

            result.replacements = new List<Query_Part_DetailResult._replacement>();
            //3.替换件处理
            if (!string.IsNullOrEmpty(result.replacementPartNo))
            {
                IEnumerable<dynamic> supersessions = repository.Invoke(CSIs.Get_Supersession_For_Sgmw, new { result.partCode });
                foreach(var supersession in supersessions)
                {
                    Query_Part_DetailResult._replacement replacement = JObject.FromObject(supersession).ToObject<Query_Part_DetailResult._replacement>();
                    replacement.brandCode = brandCode;
                    replacement.brandName = BrandDictionary.GetName(brandCode);
                    replacement.props = new List<Query_Part_DetailResult._prop>();
                    replacement.props.Add(new Query_Part_DetailResult._prop { key = "新件号", value = supersession.replacePartCode });
                    replacement.props.Add(new Query_Part_DetailResult._prop { key = "断点时间", value = supersession.breakPoint });
                    replacement.props.Add(new Query_Part_DetailResult._prop { key = "备注", value = $"{supersession.fsuDesc};{supersession.stockDesc}".Trim(';') });
                    replacement.props = replacement.props.Where(q => !string.IsNullOrEmpty(q.value)).ToList();
                    result.replacements.Add(replacement);
                }
            }

            //4.配件附加属性处理
            var props = new List<Query_Part_DetailResult._prop>
            {
                new Query_Part_DetailResult._prop { key = "件数", value = result.quantity ?? string.Empty },
                new Query_Part_DetailResult._prop { key = "备注", value = data.notes ?? string.Empty },
                new Query_Part_DetailResult._prop { key = "型号", value = data.modelNotes ?? string.Empty }
            };
            result.props = props.Where(q => !string.IsNullOrEmpty(q.value)).ToList();
            return result;
        }

        protected override dynamic GetModelsByPart(DbRESTFulRepository repository, int pageIndex, int pageSize, string brandCode, string partCode)
        {
            return repository.Invoke(CSIs.Query_Models_By_Part_For_Sgmw, new { pageIndex, pageSize, brandCode, partCode });
        }

        protected override dynamic GetHotPointsByPart(DbRESTFulRepository repository, string brandCode, string partCode, IEnumerable<string> imageIds)
        {
            return repository.Invoke(CSIs.Query_HotPoints_By_Part_For_Sgmw, new { brandCode, partCode, imageIds });
        }

        protected override List<SearchSubGroupResults> GetSearchResults(DbRESTFulRepository repository, string brandCode, string[] partCodes, string selectorId)
        {
            return repository.Invoke<SearchSubGroupResults>(CSIs.Search_SubGroups_By_PartCodes_For_Sgmw, new { brandCode, partCodes, selectorId });
        }

        protected override List<Get_Model_InfoResult._props> GetModelProps(DbRESTFulRepository repository, JObject param)
        {
            var ret = new List<Get_Model_InfoResult._props>();
            List<Query_CrumbResult> list = repository.Invoke<Query_CrumbResult>(CSIs.Get_Crumbs_App, param);
            foreach (var info in list)
            {
                if (string.IsNullOrEmpty(info.id))
                {
                    continue;
                }
                if (info.fieldCode == "series")
                {
                    ret.Add(new Get_Model_InfoResult._props { key = "厂商", value = info.name.Split('@')[0] });
                    ret.Add(new Get_Model_InfoResult._props { key = "车系", value = info.name.Split('@')[1] });
                }
                else
                {
                    ret.Add(new Get_Model_InfoResult._props { key = info.fieldName?.Replace("选择", ""), value = info.name });
                }
            }
            return ret;
        }

        protected override List<QuickPartResult> QuickQueryPartsFilterByUsage_Model(DbRESTFulRepository repository, List<QuickPartResult> parts, int selectorId)
        {
            List<QuickPartResult> ret = new List<QuickPartResult>();
            if (selectorId > 0 && parts != null && parts.Any())
            {
                List<string> partCodes = parts.Select(e => e.partCode).Distinct().ToList();

                List<Query_PartsResult> partUsages = repository.Invoke<Query_PartsResult>(CSIs.Quick_PartUsage_By_SelectorId_For_Sgmw, new { selectorId, partCodes });
                if (partUsages != null && partUsages.Any())
                {
                    foreach (var item in parts)
                    {
                        if (partUsages.FirstOrDefault(e => e.partCode == item.partCode) != null)
                        {
                            ret.Add(item);
                        }
                    }
                }
            }
            return ret;
        }
    }
}



